const Ws=require('ws');

;((Ws)=>{
    const server=new Ws.Server({port:8000});

    const init=()=>{
        bindEvent();
    }

    function bindEvent(){
        
        server.on('open',handleOpen);
        server.on('close',handleClose);
        server.on('error',handleError);
        server.on('connection',handleConnection);
        
    }
    function handleOpen(){
        console.log('websocked打开');
    }
    function handleClose(){
        console.log('websocked连接关闭');
    }
    function handleError(){
        console.log('websocked连接错误');
    }
    function handleConnection(ws){
        console.log('websocked连接');
        ws.on('message',handleMessage);
    }
    function handleMessage(msg){
        console.log('websocked收到'+msg);
        
        //找到server记录保存的客户端（clients）的所有信息（forEach）
        server.clients.forEach(function(c){

            //收到的信息广播出去
            c.send(msg);
        })

    }

    init();
})(Ws);